<template>
  <div v-elclickoutside="handleClose" ref="reference" id="wkUserSelectId"
       :class="[disabled ? 'is_disabled' : 'is_valid', { 'is_focus': visible }]"
       wrap="wrap"
       class="wk-user-select"
       @dblclick="containerClick">

    <slot name="reference"/>
    <template v-if="!$slots.reference">
      <div class="user-placeholder  text-one-line">
        <template v-for="(item, index) in showSelectedListWithLimit" :key="index">
          <span class="user-item text-one-line" style="color:#606266 ">
            {{ item[config.label] }}
            <el-icon @click.stop="deleteUser(item, index)"><Close/></el-icon>
          </span>
        </template>
      </div>

      <el-icon v-if="selectedList.length > showMaxCount">
        <MoreFilled/>
      </el-icon>
      <span class="el-icon-arrow-up">
        <el-icon v-if="visible"><ArrowDown/></el-icon>
        <el-icon v-else><ArrowUp/></el-icon>
      </span>
      <div v-if="selectedList.length == 0" class="user-placeholder text-one-line">{{ placeholder }}</div>
    </template>

    <span class="el-icon-arrow-up">
      <el-icon v-if="visible"><ArrowDown/></el-icon>
      <el-icon v-else><ArrowUp/></el-icon>
    </span>
    <WkSelectDropdown v-show="visible && !disabled" ref="popper">
      <template v-slot:default>
        <el-scrollbar ref="scrollbar" tag="div">
          <WkUser v-model:userSelectedList="dataValue"
                  :disabled="disabled"
                  :userOptionList="optionsList"
                  :props="config"
                  :radio="radio"/>
        </el-scrollbar>
      </template>
    </WkSelectDropdown>
  </div>
</template>

<script setup>
import WkSelectDropdown from '../WkDepSelect/src/SelectDropdown.vue'
import WkUser from './src/WkUser.vue'

import {valueEquals} from '/src/utils/elementui.js'
import {objDeepCopy} from '/src/utils/index.js'
import {isEmpty} from '/src/utils/types.js'
import merge from '/src/utils/merge.js'
import {useErpUserStore} from "../../../../store/modules/usererp.js";
import {useHrmStore} from "@/store/modules/hrm";


const DefaultWkUserSelect = {
  value: 'userId',
  label: 'realname',
  dataType: '', // 部门的 value label 一致，用 dataType 区分
  isList: false // 默认是树形接口，如果是列需设置为true
}

defineOptions({
  name: 'WkUserSelect',
})

const properties = defineProps({
  radio: Boolean,
  // 展示限制 0 标示展示全部
  showMaxCount: {
    type: Number,
    default: 2
  },
  placeholder: {
    type: String,
    default() {
      return '请选择'
    }
  },
  // eslint-disable-next-line vue/require-prop-types
  userSelected: {
    required: true
  },
  optionUserList: Array,
  disabled: {
    type: Boolean,
    default: false
  }
})


const optionData = reactive({
  visible: false,
  dataValue: [], // 校准传入值
  height: 34,

})


const {visible, dataValue, height} = toRefs(optionData)


const emits = defineEmits({
  'visible-change': null,
  'input': null,
  'focus': null,
  'update:userSelected': null,
  'change': null
})

// 获取deptList数据
const userList = computed(() => {
  const erpUserStore = useErpUserStore();
  return erpUserStore.userList
})
// 获取hrmDeptList数据
const hrmUserList = computed(() => {
  const erpUserStore = useHrmStore();
  return erpUserStore.hrmUserList
})

const optionsList = computed(() => {
  if (properties.optionUserList) {
    return properties.optionUserList
  }

  // 如果是一维数组，而且数据源根据请求获取，不传入 options
  if (config.value.isList) {
    return null
  }

  if (config.value.dataType === 'manage') {
    return userList.value
  } else if (config.value.dataType === 'hrm') {
    return hrmUserList.value
  }
})
// 实际展示的数据
const showSelectedListWithLimit = computed(() => {
  if (properties.showMaxCount && properties.showMaxCount > 0 && selectedList.value && selectedList.value.length > properties.showMaxCount) {
    return selectedList.value.slice(0, properties.showMaxCount)
  }
  return selectedList.value
})

// 选择的数据
const selectedList = computed(() => {
  let optionsList = []
  if (config.value.dataType === 'manage') {
    optionsList = userList.value
  } else if (config.value.dataType === 'hrm') {
    optionsList = hrmUserList.value
  }

  return optionsList.filter(item => optionData.dataValue.includes(item[config.value.value]))
})

// 合并 props
const config = computed(() => {
  const props = merge({...DefaultWkUserSelect})

  if (isEmpty(props.dataType)) {
    if (props.value === 'userId') {
      props.dataType = 'manage'
    } else if (props.value === 'employeeId') {
      props.dataType = 'hrm'
    }
  }
  return props
})

watch(visible, (val) => {
  emits('visible-change', val)
})

watch(() => properties.userSelected, (newVal, oldVal) => {
  verifyValue()
})

/**
 * 更新值
 */
watch(dataValue, (newValue) => {
  if (properties.radio) {
    emits('input', optionData.dataValue && optionData.dataValue.length ? optionData.dataValue[0] : '')
  } else {
    emits('input', optionData.dataValue)
  }
  emits('update:userSelected', optionData.dataValue)
})

const tagsRef = ref()

function resetHeight() {
  if (tagsRef.value) {
    nextTick(() => {
      optionData.height = tagsRef.value.clientHeight > 34 ? tagsRef.value.clientHeight + 6 : 34
    })
  } else {
    optionData.height = 34
  }
}

watch(showSelectedListWithLimit, () => {
  resetHeight()
}, {
  immediate: true
})


function created() {
  verifyValue()
  requestUserList()
}

created()


/**
 * 处理值逻辑
 */
function verifyValue() {
  // 多选的默认值 校准为数组  单选校准为number
  if (!properties.radio && !Array.isArray(properties.userSelected)) {
    emits('input', [])
  }

  if (properties.radio && (Array.isArray(properties.userSelected) || properties.userSelected === null || properties.userSelected === undefined)) {
    emits('input', '')
  }

  if (properties.radio) {
    if (properties.userSelected !== optionData.dataValue) {
      if (!isEmpty(properties.userSelected)) {
        optionData.dataValue = [parseInt(properties.userSelected)]
      } else {
        optionData.dataValue = []
      }
    }
  } else {
    if (!valueEquals(properties.userSelected, optionData.dataValue)) {
      if (properties.userSelected && properties.userSelected.length) {
        const firstItem = properties.userSelected[0]
        if (firstItem[config.value.value]) {
          optionData.dataValue = properties.userSelected.map(item => item[config.value.value])
        } else {
          optionData.dataValue = objDeepCopy(properties.userSelected)
        }
      } else {
        optionData.dataValue = []
      }
    }
  }
}

/**
 * 获取请求
 */
function requestUserList() {
  const erpUserStore = useErpUserStore()
  const hrmStore = useHrmStore()
  if (config.value.dataType === 'manage') {
    // 以缓存中的全部数据为id转对象的源
    erpUserStore.debounceGetUserList()
  } else if (config.value.dataType === 'hrm') {
    hrmStore.debounceGetHrmUserList()
  }
}

function handleClose() {
  optionData.visible = false
}


/**
 * 删除
 */
function deleteUser(item) {
  console.log("deleteUser", item)
  if (!item.disabled && !properties.disabled) {
    for (let index = 0; index < optionData.dataValue.length; index++) {
      const id = optionData.dataValue[index]
      if (id == item[config.value.value]) {
        optionData.dataValue.splice(index, 1)
        break
      }
    }
  }
}

function containerClick() {
  if (!properties.disabled) {
    optionData.visible = !optionData.visible
  }
}
</script>


<style lang="scss" scoped>
.wk-user-select {
  height: 34px;
  position: relative;
  border-radius: 4px;
  font-size: 13px;
  background-color: white;
  border: 1px solid #e6e6e6;
  color: #333333;
  width: 180px;
  padding: 0 20px 0 5px;
  cursor: pointer;

  .user-item {
    padding: 5px 15px 5px 5px;
    background-color: #F3F7FF;
    border-radius: 4px;
    margin: 3px;
    max-width: 80px;
    position: relative;

    &.is-hide {
      background-color: #f2f2f2;
      color: #999;
    }
  }

  .user-placeholder {
    color: #ddd;
    line-height: 34px;
    cursor: pointer;
    user-select: none;
  }

  .delete-icon {
    color: #999;
    cursor: pointer;
    position: absolute;
    top: 8px;
    right: 2px;

    &:hover {
      color: #2362FB;
    }
  }

  &:hover {
    border-color: #c0c4cc;
  }
}

.wk-user-select.is_disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  cursor: not-allowed;

  .user-item {
    background-color: #f0f4f8ea;
    color: #c0c4cc;
    cursor: not-allowed;
  }

  .delete-icon {
    color: #c0c4cc;
    cursor: not-allowed;
  }

  .user-placeholder {
    color: #c0c4cc;
    cursor: not-allowed;
  }
}

.wk-user-select.is_valid:hover {
  border-color: #c0c4cc;
}

.wk-user-select.is_focus {
  border-color: #2362FB !important;
}

.el-select__tags {
  padding-right: 30px;
}

.el-icon-more {
  position: absolute;
  top: 5px;
  right: 20px;
  padding: 6px 10px;
  font-size: 12px;
  background-color: #F3F7FF;
  color: #666;
  border-radius: 4px;

  &:hover {
    background-color: #2362FB;
    color: white;
  }
}

.el-icon-arrow-up {
  position: absolute;
  top: 10px;
  right: 5px;
  transition: transform .3s;
  color: #c0c4cc;
  font-size: 14px;
  transition: transform .3s;
  transform: rotate(180deg);
  cursor: pointer;
}

.el-icon-arrow-up.is-reverse {
  transform: rotate(0deg);
}
</style>
